package com.caht.intercept;

import cn.hutool.http.HttpStatus;
import com.caht.Uilts.JWTUtils;
import com.caht.constant.JwtClaimsConstant;
import com.caht.context.BaseContext;
import com.caht.properties.jwtProperties;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登入时 进行拦截
 */
@Component
@Slf4j
public class JWTLoginUserInstantiator implements  HandlerInterceptor {
    @Autowired
    private jwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("加载路径:{}",request.getRequestURI());
        // 如果不是HandlerMethod类型，直接返回true
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 从请求头中获取token
        String token = request.getHeader(jwtProperties.getUsersecretkey());
        // 如果token为空，直接返回false
        if (token == null) {
            return false;
        }
        // 解析token
        Claims claims = JWTUtils.analysisToken(token,jwtProperties.getUsersecret());
        // 获取用户id
        Long userid = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
        // 设置当前用户id
        BaseContext.setCurrentId(userid);
        // 继续执行下一步
        return true;
    }
}
